# -*- coding: UTF-8 -*-
from . import api
from flask import render_template, request, send_file, make_response, redirect, jsonify
from app import util, PAGE_NUM
from dbConnection.MysqlConn import Mysql
import urllib, time


# 商家剩余洗车次数
@api.route('/api/business/content', methods=['post'])
def content():
    data = {}
    data['code'] = 400
    data['msg'] = '获取失败'
    data['num'] = 0
    try:
        openid = request.values.get('openid', '')
        user = get_user(openid)
        if user is None:
            data['code'] = 402
            data['msg'] = '用户不存在'
            return util.to_json(data)
        business = get_business(user['bid'])
        if business is None or business['bid'] == 0:
            data['code'] = 403
            data['msg'] = '账号没有关联商家'
            return util.to_json(data)
        data['num'] = business['wash_num']
    except Exception as e:
        print e
        data['code'] = 500
        data['msg'] = '系统错误'
    return util.to_json(data)


# 商家赠送详情
@api.route('/api/give_list', methods=['post'])
def give_list():
    data = {}
    data['code'] = 400
    data['msg'] = '获取失败'
    data['count'] = 0
    data['data'] = []
    data['num'] = PAGE_NUM
    data['total'] = 0
    try:
        openid = request.values.get('openid', '')
        page = request.values.get('page', 1)
        day = request.values.get('day')
        user = get_user(openid)
        if user is None:
            data['code'] = 402
            data['msg'] = '用户不存在'
            return util.to_json(data)
        business = get_business(user['bid'])
        if business is None or business['bid'] == 0:
            data['code'] = 403
            data['msg'] = '账号没有关联商家'
            return util.to_json(data)
        c_num = (int(page) - 1) * PAGE_NUM
        sql = "select g.*, r.name, u.wxNickName, c.use_num, r.num, ifnull(a.wxNickName, '') give_name FROM business_give_log g LEFT JOIN recharge r ON r.id = g.rid " \
              "LEFT JOIN car_users u ON u.uid = g.uid LEFT JOIN car_users a ON a.uid = g.give_uid LEFT JOIN user_taocan c ON c.id = g.tid WHERE g.bid = '%s' " % business['bid']
        sql2 = "select count(*) con FROM business_give_log WHERE bid = '%s'" % business['bid']
        if day:
            day_list = str(day).split('-')
            first, last = util.getMonthFirstDayAndLastDay(day_list[0], day_list[1])
            sql += " and g.add_time >= '%s' and g.add_time <= '%s'" % (str(first), str(last) + ' 23:59:59')
            sql2 += " and add_time >= '%s' and add_time <= '%s'" % (str(first), str(last) + ' 23:59:59')
        sql += "ORDER BY g.add_time desc limit %d, %d" % (c_num, PAGE_NUM)
        mysql = Mysql()
        res = mysql.getAll(sql, None)
        cont = mysql.getOne(sql2, None)
        mysql.dispose()
        if res:
            for d in res:
                d['add_time'] = str(d['add_time'])
                d['url'] = urllib.quote(business_url(str(d['bid']), str(d['id'])))
                data['total'] += int(d['num']) if d['num'] else 0
                # d['give_name'] = d['give_name'] if d['give_name'] else ''
            data['code'] = 200
            data['data'] = res
            data['msg'] = '获取成功'
        data['count'] = cont['con'] if cont else 0
    except Exception as e:
        print e
        data['code'] = 500
        data['msg'] = '系统错误'
    return util.to_json(data)


# 商家购买记录
@api.route('/api/buy_log', methods=['post'])
def buy_log():
    data = {}
    data['code'] = 400
    data['msg'] = '获取失败'
    data['count'] = 0
    data['data'] = []
    data['num'] = PAGE_NUM
    data['total'] = 0
    try:
        openid = request.values.get('openid', '')
        page = request.values.get('page', 1)
        day = request.values.get('day')
        user = get_user(openid)
        if user is None:
            data['code'] = 402
            data['msg'] = '用户不存在'
            return util.to_json(data)
        business = get_business(user['bid'])
        if business is None or business['bid'] == 0:
            data['code'] = 403
            data['msg'] = '账号没有关联商家'
            return util.to_json(data)
        c_num = (int(page) - 1) * PAGE_NUM
        sql = "select p.*, s.num suit_num, s.name FROM business_pay_log p LEFT JOIN business_suit s ON s.suit_id = p.suit_id" \
              " WHERE p.bid = '%s'" % user['bid']
        sql2 = "select count(*) con FROM business_pay_log WHERE bid = '%s'" % user['bid']
        if day:
            day_list = str(day).split('-')
            first, last = util.getMonthFirstDayAndLastDay(day_list[0], day_list[1])
            sql += " and p.add_time >= '%s' and p.add_time <= '%s'" % (str(first), str(last) + ' 23:59:59')
            sql2 += " and add_time >= '%s' and add_time <= '%s'" % (str(first), str(last) + ' 23:59:59')
        sql += " order by p.add_time desc limit %d, %d" % (c_num, PAGE_NUM)
        mysql = Mysql()
        res = mysql.getAll(sql, None)
        cont = mysql.getOne(sql2, None)
        mysql.dispose()
        if res:
            for d in res:
                d['add_time'] = str(d['add_time'])
                d['recharge_price'] = str(d['recharge_price'])
                d['pay_money'] = str(d['pay_money'])
                data['total'] += int(d['num'])
            data['code'] = 200
            data['data'] = res
            data['msg'] = '获取成功'
        data['count'] = cont['con'] if cont else 0
    except Exception as e:
        print e
        data['code'] = 500
        data['msg'] = '系统错误'
    return util.to_json(data)


# 商家充值记录
@api.route('/api/recharge_log', methods=['post'])
def recharge_log():
    data = {}
    data['code'] = 400
    data['msg'] = '获取失败'
    data['count'] = 0
    data['data'] = []
    data['num'] = PAGE_NUM
    data['total'] = 0
    try:
        openid = request.values.get('openid', '')
        page = request.values.get('page', 1)
        day = request.values.get('day')
        user = get_user(openid)
        if user is None:
            data['code'] = 402
            data['msg'] = '用户不存在'
            return util.to_json(data)
        business = get_business(user['bid'])
        if business is None or business['bid'] == 0:
            data['code'] = 403
            data['msg'] = '账号没有关联商家'
            return util.to_json(data)
        c_num = (int(page) - 1) * PAGE_NUM
        sql = "select * FROM business_recharge WHERE bid = '%s'" % business['bid']
        sql2 = "select count(*) con FROM business_recharge WHERE bid = '%s'" % business['bid']
        if day:
            day_list = str(day).split('-')
            first, last = util.getMonthFirstDayAndLastDay(day_list[0], day_list[1])
            sql += " and add_time >= '%s' and add_time <= '%s'" % (str(first), str(last) + ' 23:59:59')
            sql2 += " and add_time >= '%s' and add_time <= '%s'" % (str(first), str(last) + ' 23:59:59')
        sql += " order by add_time desc limit %d, %d" % (c_num, PAGE_NUM)
        mysql = Mysql()
        res = mysql.getAll(sql, None)
        cont = mysql.getOne(sql2, None)
        mysql.dispose()
        if res:
            for d in res:
                d['add_time'] = str(d['add_time'])
                data['total'] += int(d['pay_money'])
            data['code'] = 200
            data['data'] = res
            data['msg'] = '获取成功'
        data['count'] = cont['con'] if cont else 0
    except Exception as e:
        print e
        data['code'] = 500
        data['msg'] = '系统错误'
    return util.to_json(data)


# 商家详情
@api.route('/api/business_detail', methods=['post'])
def business_detail():
    data = {}
    data['code'] = 400
    data['msg'] = '获取失败'
    try:
        openid = request.values.get('openid', '')
        user = get_user(openid)
        if user is None:
            data['code'] = 402
            data['msg'] = '用户不存在'
            return util.to_json(data)
        business = get_business(user['bid'])
        if business is None or business['bid'] == 0:
            data['code'] = 403
            data['msg'] = '账号没有关联商家'
            return util.to_json(data)
        data['uid'] = user['uid']
        data['header'] = user['wxHeadImg']
        data['uname'] = user['wxNickName']
        data['bid'] = business['bid']
        data['nickname'] = business['nickname']
        data['num'] = business['wash_num']
        data['balance'] = str(business['money'])
        data['code'] = 200
        data['msg'] = '获取成功'
    except Exception as e:
        print e
        data['code'] = 500
        data['msg'] = '系统错误'
    return util.to_json(data)


# 生成商家赠送二维码
@api.route('/api/buy_wash_code', methods=['post'])
def buy_wash_code():
    data = {}
    data['code'] = 400
    data['msg'] = '订单不存在'
    try:
        openid = request.values.get('openid', '')
        rid = request.values.get('rid')
        user = get_user(openid)
        if user is None:
            data['code'] = 402
            data['msg'] = '用户不存在'
            return util.to_json(data)
        business = get_business(user['bid'])
        if business is None or business['bid'] == 0:
            data['code'] = 403
            data['msg'] = '账号没有关联商家'
            return util.to_json(data)
        recharge = get_recharge_detail(rid)
        if recharge is None:
            data['code'] = 405
            data['msg'] = '套餐错误'
            return util.to_json(data)
        if int(recharge['num']) > int(business['wash_num']):
            data['msg'] = '剩余次数不足'
            data['code'] = 406
            return util.to_json(data)
        res = add_buy_log(user['bid'], rid, user['uid'])
        if res > 0:
            data['code'] = 200
            data['msg'] = '获取成功'
            data['url'] = urllib.quote(business_url(user['bid'], res))
            update_wash_num(user['bid'], recharge['num'])
    except Exception as e:
        print e
        data['code'] = 500
        data['msg'] = '系统错误'
    return util.to_json(data)


# 商家余额支付购买洗车卷
@api.route('/api/business/balance_pay', methods=['post'])
def balance_pay():
    data = {}
    data['code'] = 400
    data['msg'] = '购买失败'
    try:
        openid = request.values.get('openid', '')
        rid = request.values.get('rid')
        user = get_user(openid)
        if user is None:
            data['code'] = 402
            data['msg'] = '用户不存在'
            return util.to_json(data)
        business = get_business(user['bid'])
        if business is None or business['bid'] == 0:
            data['code'] = 403
            data['msg'] = '账号没有关联商家'
            return util.to_json(data)
        suit = get_business_suit(rid)
        if suit is None:
            data['code'] = 405
            data['msg'] = '套餐不存在'
            return util.to_json(data)
        if float(suit['price']) > float(business['money']):
            data['code'] = 406
            data['msg'] = '余额不足'
            return util.to_json(data)
        res = add_business_pay_log(user['uid'], suit, user['bid'])
        if res > 0:
            update_user_wash(user['bid'], suit['num'], suit['price'], rid, business['buy_suit'])
            data['code'] = 200
            data['msg'] = '购买成功'
    except Exception as e:
        print e
        data['code'] = 500
        data['msg'] = '系统错误'
    return util.to_json(data)


# 商家赠送套餐列表
@api.route('/api/business/meal', methods=['post'])
def business_meal():
    data = {}
    data['code'] = 400
    data['msg'] = '获取失败'
    data['data'] = []
    try:
        openid = request.values.get('openid', '')
        user = get_user(openid)
        if user is None:
            data['code'] = 402
            data['msg'] = '用户不存在'
            return util.to_json(data)
        business = get_business(user['bid'])
        if business is None or business['bid'] == 0:
            data['code'] = 403
            data['msg'] = '账号没有关联商家'
            return util.to_json(data)
        taocan = get_business_taocan(business['wash_num'])
        if taocan:
            data['code'] = 200
            data['msg'] = '获取成功'
            data['data'] = taocan
            data['num'] = business['wash_num']
    except Exception as e:
        print e
        data['code'] = 500
        data['msg'] = '系统错误'
    return util.to_json(data)


# 商家购买商品列表
@api.route('/api/business/goods_list', methods=['post'])
def goods_list():
    data = {}
    data['code'] = 400
    data['msg'] = '获取失败'
    data['data'] = []
    try:
        openid = request.values.get('openid', '')
        user = get_user(openid)
        if user is None:
            data['code'] = 402
            data['msg'] = '用户不存在'
            return util.to_json(data)
        business = get_business(user['bid'])
        if business is None or business['bid'] == 0:
            data['code'] = 403
            data['msg'] = '账号没有关联商家'
            return util.to_json(data)
        res = business_suit_list(business['bid'])
        if res:
            for d in res:
                d['price'] = str(d['price'])
            data['data'] = res
            data['code'] = 200
            data['msg'] = '获取成功'
            data['money'] = str(business['money'])
            data['num'] = str(business['wash_num'])
    except Exception as e:
        print e
        data['code'] = 500
        data['msg'] = '系统错误'
    return util.to_json(data)


# 获取用户详情
def get_user(openid):
    sql = "select * FROM car_users WHERE wxOpenId = '%s'" % openid
    mysql = Mysql()
    res = mysql.getOne(sql, None)
    mysql.dispose()
    return res


# 获取商家详情
def get_business(bid):
    sql = "select * FROM user_business WHERE bid = '%s'" % bid
    mysql = Mysql()
    res = mysql.getOne(sql, None)
    mysql.dispose()
    return res


def business_url(bid, gid):
    url_str = "http://gz.deyiauto.com/wash/success.html?bid=%s&gid=%s" % (bid, gid)
    wx_str = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx087bed01c194a785&redirect_uri=%s" \
             "&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect" % urllib.quote(url_str)
    return wx_str


# 获取套餐详情
def get_recharge_detail(rid):
    sql = "select * FROM recharge WHERE id = '%s'" % rid
    mysql = Mysql()
    res = mysql.getOne(sql, None)
    mysql.dispose()
    return res


# 生成商家赠送记录
def add_buy_log(bid, rid, uid):
    sql = "insert INTO business_give_log(bid, rid, give_uid, add_time) VALUES ('%s', '%s', '%s', now())" % \
          (bid, rid, uid)
    mysql = Mysql()
    res = mysql.insertOne(sql, None)
    mysql.dispose()
    return res


# 更新商家洗车次数
def update_wash_num(bid, num):
    sql = "update user_business SET wash_num = wash_num - '%s' WHERE bid = '%s'" % (num, bid)
    mysql = Mysql()
    res = mysql.update(sql, None)
    mysql.dispose()


# 获取商家可以赠送的套餐列表
def get_business_taocan(num):
    sql = "select id, price, num, name FROM recharge WHERE status = 1 and num <= %s ORDER BY num asc" % num
    mysql = Mysql()
    res = mysql.getAll(sql, None)
    mysql.dispose()
    return res


# 查询商家套餐
def get_business_suit(rid):
    sql = "select * FROM business_suit WHERE suit_id = '%s'" % rid
    mysql = Mysql()
    res = mysql.getOne(sql, None)
    mysql.dispose()
    return res


# 新增商家购买记录
def add_business_pay_log(uid, res, bid):
    order_num = str(uid) + '_' + str(res['suit_id']) + '_1_' + str(int(time.time()*1000))
    sql = "insert INTO business_pay_log(bid, suit_id, recharge_num, recharge_name, recharge_price, pay_money, uid, " \
          "order_num, add_time) VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', now())"\
          % (bid, res['suit_id'], res['num'], res['name'], res['price'], res['price'], uid, order_num)
    mysql = Mysql()
    res = mysql.insertOne(sql, None)
    mysql.dispose()
    return res


# 跟新用户的洗车次数
def update_user_wash(bid, wash_num, moeny, suit_id, suit_str):
    if suit_str == '':
        buy_suit = str(suit_id)
    else:
        buy_list = suit_str.split(',')
        if str(suit_id) in buy_list:
            buy_suit = suit_str
        else:
            buy_suit = suit_str + ',' + str(suit_id)
    sql = "update user_business SET wash_num = wash_num + '%s', money = money - '%s', buy_suit = '%s'  WHERE bid = '%s'"\
          % (wash_num, moeny, buy_suit, bid)
    mysql = Mysql()
    res = mysql.update(sql, None)
    mysql.dispose()


# 获取商家套餐列表
def business_suit_list(bid):
    sql = "select suit_id,name, price, num,ones FROM business_suit WHERE status = 1 ORDER BY weight ASC, suit_id desc"
    mysql = Mysql()
    res = mysql.getAll(sql, None)
    mysql.dispose()
    business_str = get_business(bid)
    suit_list = []
    if business_str:
        suit_list = business_str['buy_suit'].split(',')
    if res:
        res = list(res)
        for d in res:
            if d['ones'] == 1 and str(d['suit_id']) in suit_list:
                res.remove(d)
    return res


# 查询是否有洗车次数
# def car_wash_num(uid):
#     sql = "SELECT (sum(recharge_num) - sum(use_num)) wash_num from user_taocan where uid = '%s' and now() < end_time" % uid
#     mysql = Mysql()
#     res = mysql.getOne(sql, None)
#     mysql.dispose()
#     num = int(res['wash_num']) if res['wash_num'] else 0
#     return num